package com.cetccloud.ap.vertx.proxy;

import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetClientOptions;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetSocket;

/**
 * @ClassName Proxy
 * @Description TODO
 * @Author superz
 * @Date 2021/4/20 23:52
 * @Version 1.0
 **/
public class Proxy {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx(new VertxOptions().setWorkerPoolSize(128));
        EventBus eventBus = vertx.eventBus();

        NetClientOptions options = new NetClientOptions().setConnectTimeout(10000);
        NetClient client = vertx.createNetClient(options);
        client.connect(80, "150.138.227.103", res -> {
            if (res.succeeded()) {
                System.out.println("Connected!");
                NetSocket socket = res.result();

                eventBus.consumer("send").handler(message -> {
                    Buffer buffer = (Buffer) message.body();
                    System.out.println("代理发送: " + buffer.length());
                    socket.write(buffer);
                });

                socket.handler(buffer -> {
                    System.out.println("代理接收: " + buffer.length());
                    eventBus.send("receive", buffer);
                });
            } else {
                System.out.println("Failed to connect: " + res.cause().getMessage());
            }
        });


        NetServer server = vertx.createNetServer();
        server.connectHandler(socket -> {
            // Handle the connection in here
            socket.handler(buffer -> {
                System.out.println("发起请求: " + buffer.length());
                eventBus.send("send", buffer);
            });

            eventBus.consumer("receive").handler(message -> {
                Buffer buffer = (Buffer) message.body();
                System.out.println("请求响应: " + buffer.length());
                socket.write(buffer);
            });
        });
        server.listen(80, "127.0.0.1", res -> {
            if (res.succeeded()) {
                System.out.println("Server is now listening!");
            } else {
                System.out.println("Failed to bind!");
            }
        });

    }
}
